using System;
using System.Reflection.Emit;
using Pine.Core;
using Pine.SourceParser.Tree;

namespace Pine.CodeGen
{
	public static class DeclarationStatementCodeGenerator
	{
		public static void GenerateBytecode(Context ctx, Statement stmt)
		{
			LocalBuilder newScope = ctx.il.DeclareLocal(typeof(IScope));
			ctx.il.Emit(OpCodes.Ldloc, ctx.scope);
			ctx.il.Emit(OpCodes.Newobj, typeof(BlockScope).GetConstructor(new Type[] { typeof(IScope) }));
			ctx.il.Emit(OpCodes.Stloc, newScope);
			
			ctx.scope = newScope;
			
			ctx.il.Emit(OpCodes.Ldloc, ctx.list);
			ctx.il.Emit(OpCodes.Call, typeof(ValueList).GetMethod("Clear"));
			
			DeclarationStatement decl = (DeclarationStatement) stmt;
			if (decl.right != null) {
				CodeGenerator.ParseRightList(ctx, decl.right);
			}
			
			foreach (VariableDeclarationElement elem in decl.left.declarations) {
				//TODO: Varargs
				LocalBuilder scopeval = ctx.il.DeclareLocal(typeof(Value));
				CodeUtilities.MakeGetListValue(ctx.il, ctx.list, elem.key, scopeval);
				CodeUtilities.MakeScopeDeclare(ctx.il, ctx.scope, elem.isConst, scopeval, elem.name);
			}
		}
	}
}

